package com.ctjsoft.collect;

import java.util.*;

/**
 * 测试Collection接口
 *
 * @author: liaoyy
 * @date: Created in 2021/11/18 22:37
 */
public class IteratorDemo {

    public static void main(String[] args) {
        Collection<String> collection = new ArrayList<>();
        collection.add("1");
        collection.add("2");
        collection.add("3");
        collection.add("4");

        //获取迭代器
        Iterator<String> iterator = collection.iterator();
        //使用迭代器hasNext()方法判断迭代位置，使用next()获取元素
        while (iterator.hasNext()) {
            String next = iterator.next();
            System.out.println(next);
        }

        //如果需要再次遍历，则需重置迭代器。否则会抛出NoSuchElementException异常
        iterator = collection.iterator();
        //重启迭代器后的二次遍历
        System.out.println("----二次遍历----");
        while (iterator.hasNext()) {
            String next = iterator.next();
            System.out.println(next);
        }
    }
}
